package com.warrior.controler;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.warrior.bean.Result;
import com.warrior.bean.ResultGenerator;
import com.warrior.entity.WorkerNode;
import com.warrior.service.IWorkerNodeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * DB WorkerID Assigner for UID Generator 前端控制器
 * </p>
 *
 * @author lqh
 * @since 2020-05-22
 */
@RestController
@RequestMapping("/workernode")
public class WorkerNodeController {

    @Resource
    private IWorkerNodeService workerNodeService;

    @RequestMapping("/list")
    public Result list() {
        Page<WorkerNode> page = new Page<>();
        return ResultGenerator.successResult(workerNodeService.selectPage(page));
    }

    @PostMapping("/get")
    public Result getNodeId(@RequestBody WorkerNode entity) {

        if (entity == null) {
            return ResultGenerator.failResult("entity is null.");
        }

        if (StringUtils.isBlank(entity.getIp()) || StringUtils.isBlank(entity.getHostName())) {
            return ResultGenerator.failResult("ip or hostName is null.");
        }

        //根据 HOST_NAME  IP 获取服务器的节点
        //Wrapper<WorkerNode> wrapper = new EntityWrapper<>();
        //wrapper.eq("IP", entity.getIp()).eq("HOST_NAME", entity.getHostName());

        //List<WorkerNode> list = workerNodeService.selectList(wrapper);
        List<WorkerNode> list = Arrays.asList();

        if (CollectionUtils.isEmpty(list)) {
            workerNodeService.insert(entity);
            return ResultGenerator.successResult(entity.getId());
        } else {
            return ResultGenerator.successResult(list.get(0).getId());
        }

    }


}

